package com.teama4.shop.controller;


import com.github.pagehelper.PageHelper;
import com.teama4.shop.annotation.NeedLogin;
import com.teama4.shop.domain.*;
import com.teama4.shop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class PagesController {

    @Autowired
    private UserService userService;

    @Autowired
    private DeliveryAddressService deliveryAddressService;

    @Autowired
    private SpecificationService specificationService;

    @Autowired
    private CartService cartService;

    @Autowired
    private CommodityCollectService commodityCollectService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private StoreCollectService storeCollectService;

    @Autowired
    CommodityService commodityService;

    @Autowired
    SearchServiceExt searchServiceExt;

    @Autowired
    OrdersService ordersService;
    @Autowired
    CommodityOrdersService commodityOrdersService;
    @Autowired
    CommoditySpecificationServiceExt commoditySpecificationServiceExt;

    @Autowired
    ViewHistoryService viewHistoryService;
    @Autowired
    private ServiceService serviceService;

    @Autowired
    private EvaluateService evaluateService;

    @Autowired
    private EvaluatePicService evaluatePicService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 判断是否已经评价
     *
     * @param orderId
     * @param specificationId
     * @return
     */
    private boolean isHavaEva(Integer userId, Integer orderId, Integer specificationId) {

        EvaluateExample evaluateExample = new EvaluateExample();
        evaluateExample.createCriteria().andOrderIdEqualTo(orderId)
                .andSpecificationIdEqualTo(specificationId)
                .andUserIdEqualTo(userId);

        List<Evaluate> evaluates = evaluateService.selectByExample(evaluateExample);
        if (evaluates.size() > 0) {
            return true;
        }
        return false;

    }

    /**
     * 获得购物车列表
     *
     * @param userId
     * @return
     */

    private CartExt getCartByUserId(Integer userId, int pageNum, int pageSize) {
        CartExt cartExt = cartService.selectCartByUserId(userId, pageNum, pageSize);
        if (cartExt.getCartSpeComs().size() > 0) {
            Iterator<CartSpeCom> iterator = cartExt.getCartSpeComs().iterator();
            while (iterator.hasNext()) {
                CartSpeCom next = iterator.next();
                double sumPrice = next.getPrice() * next.getCommodityCount();
                next.setSumPrice(new BigDecimal(sumPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
            return cartExt;
        }
        return null;
    }

    /**
     * 获得购物车总价
     *
     * @param carts
     * @return
     */
    private Double getCartsPrice(List<CartSpeCom> carts) {
        Double price = 0.00;
        if (carts.size() > 0) {
            Iterator<CartSpeCom> iterator = carts.iterator();
            while (iterator.hasNext()) {
                CartSpeCom next = iterator.next();

                price += next.getPrice() * next.getCommodityCount();
            }
            return new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        return new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 获得购物车总量
     *
     * @param carts
     * @return
     */
    private int getCartsCount(List<CartSpeCom> carts) {
        int count = 0;
        if (carts.size() > 0) {
            Iterator<CartSpeCom> iterator = carts.iterator();
            while (iterator.hasNext()) {
                CartSpeCom next = iterator.next();
                count += next.getCommodityCount();
            }
            return count;
        }
        return count;
    }

    /**
     * 查看商品是几级分类
     */
    private Integer getCategoryLevel(Integer categoryId) {
        Category category = categoryService.selectByPrimaryKey(categoryId);
        if (category != null) {
            int level = 1;
            for (; category.getParentCategory() != null; ) {
                category = categoryService.selectByPrimaryKey(category.getParentCategory());
                if (category != null) {
                    level++;
                } else {
                    //没有父分类
                    return -2;
                }
            }
            return level;
        }
        //没有此分类
        return -1;

    }

    /**
     * 查看商品是几级分类
     */
    private boolean isCategoryLastLevel(Integer categoryId) {
        CategoryExample CE = new CategoryExample();
        CE.createCriteria().andParentCategoryEqualTo(categoryId);

        List<Category> categories = categoryService.selectByExample(CE);
        if (categories.size() > 0) {
            return false;
        }
        return true;

    }

    /**
     * 跳转首页
     */
    @RequestMapping("/index")
    public String index(HttpServletRequest req, Model model) {

        //查询推荐信息
        List<Commodity> commodities = new ArrayList<>();
        //判断是否登录
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            User user = userService.selectByPrimaryKey(userId);
            String RGStr = user.getRecommendedGoods();
            RGStr = RGStr.substring(0,RGStr.length()-1);
            String[] RGSs = RGStr.split(",");
            List<Integer> RGSList = new ArrayList<>();
            for (int i=0;i<RGSs.length;i++){
                RGSList.add(Integer.valueOf(RGSs[i]));
            }
            CommodityExample commodityExample = new CommodityExample();
            commodityExample.createCriteria().andIdIn(RGSList);
            PageHelper.startPage(1,5);
            commodities= commodityService.selectByExample(commodityExample);
        }else {
            CommodityExample commodityExample = new CommodityExample();
            commodityExample.createCriteria().andBayCountGreaterThanOrEqualTo(30)
                    .andViewCountGreaterThanOrEqualTo(30)
                    .andComPriceGreaterThanOrEqualTo(20.00);
            PageHelper.startPage(1,5);
            commodities= commodityService.selectByExample(commodityExample);
        }

        model.addAttribute("commodities",commodities);
        model.addAttribute("pageNum",1);
        return "index";
    }

    /**
     * categoryLevel
     * 跳转登录页面
     */
    @RequestMapping("/login")
    public String login(Model model) {
        return "homeFramework/login";

    }

    /**
     * 跳转修改密码页面
     */
    @NeedLogin
    @RequestMapping("/changePassword")
    public String changePassword(HttpServletRequest req, Model model) {
        return "homeFramework/change-password";
    }

    /**
     * 跳转修改邮箱页面
     */
    @NeedLogin
    @RequestMapping("/changeEmail")
    public String changeEmail(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");

            User user = userService.selectByPrimaryKey(userId);

            if (user.getEmail() != null && !user.getEmail().equals("")) {
                model.addAttribute("email", user.getEmail());
            } else {
                model.addAttribute("email", "unexit");
            }
            return "homeFramework/change-email";
        }
         return "homeFramework/login";

    }

    /**
     * 跳转修改手机号页面
     */
    @NeedLogin
    @RequestMapping("/changePhone")
    public String changePhone(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            User user = userService.selectByPrimaryKey(userId);

            if (user.getPhone() != null && !user.getPhone().equals("")) {
                model.addAttribute("phone", user.getPhone());
            } else {
                model.addAttribute("phone", "unexit");
            }
            return "homeFramework/change-phone";
        }
         return "homeFramework/login";
    }

    /**
     * 跳转实名认证页面
     */
    @NeedLogin
    @RequestMapping("/myIdcard")
    public String myIdcard(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {

            //发送购物车信息
            Integer userId = (Integer) session.getAttribute("userId");
            User user = userService.selectByPrimaryKey(userId);

            if (user.getPhone() != null && !user.getPhone().equals("")) {
                model.addAttribute("phone", user.getPhone());
            } else {
                model.addAttribute("phone", "unexit");
            }

            return "homeFramework/my-IdCard";
        }
         return "homeFramework/login";

    }

    @NeedLogin
    @RequestMapping("/myPayPassword")
    public String myPayPassword(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {

            Integer userId = (Integer) session.getAttribute("userId");

            User user = userService.selectByPrimaryKey(userId);

            if (user.getPhone() != null && !user.getPhone().equals("")) {
                model.addAttribute("phone", user.getPhone());
            } else {
                model.addAttribute("phone", "unexit");
            }
            if (user.getPayPassword() != null && !user.getPayPassword().equals("")) {
                model.addAttribute("payPassword", user.getPayPassword());
            } else {
                model.addAttribute("payPassword", "unexit");
            }
            return "homeFramework/my-payPassword";
        }
         return "homeFramework/login";

    }

    /**
     * 跳转账户安全页面
     */
    @NeedLogin
    @RequestMapping("/accountSecurity")
    public String accountSecurity(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");

            return "homeFramework/account-security";
        }
         return "homeFramework/login";

    }

    /**
     * 跳转添加收货地址页面
     */
    @NeedLogin
    @RequestMapping("/myAddressAdd")
    public String myAddressAdd(HttpServletRequest req) {
        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {

            return "homeFramework/my-address-add";
        }
         return "homeFramework/login";

    }

    /**
     * 跳转修改收货地址页面
     */
    @NeedLogin
    @RequestMapping("/myAddressEdit")
    public String myAddressEdit(HttpServletRequest req, Model model, Integer id) {
        HttpSession session = req.getSession(false);
        if (id != null) {
            if (session != null && session.getAttribute("userId") != null) {
                Integer userId = (Integer) session.getAttribute("userId");
                DeliveryAddress deliveryAddress = deliveryAddressService.selectByPrimaryKey(id);
                model.addAttribute("deliveryAddress", deliveryAddress);
                if (deliveryAddress.getUserId().equals(userId)) {
                    return "homeFramework/my-address-edit";
                }
            }
        } else {
            return "homeFramework/myAddress";
        }
         return "homeFramework/login";

    }

    /**
     * 跳转注册页面
     */
    @RequestMapping("/register")
    public String register() {
        return "homeFramework/register";
    }


    /**
     * 跳转我的信息页面
     */
    @NeedLogin
    @RequestMapping("/myInfo")
    public String myInfo(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            User user = userService.selectByPrimaryKey((Integer) session.getAttribute("userId"));
            model.addAttribute("user", user);
            return "homeFramework/my-info";
        }
         return "homeFramework/login";
    }

    /**
     * 跳转修改个人信息页面页面
     */
    @NeedLogin
    @RequestMapping("/myInfoEdit")
    public String myInfoEdit(HttpServletRequest req, Model model) throws ParseException {
        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            User user = userService.selectByPrimaryKey((Integer) session.getAttribute("userId"));
            model.addAttribute("user", user);
            return "homeFramework/my-info-edit";
        }
         return "homeFramework/login";
    }

    /**
     * 跳转浏览记录页面
     */
    @NeedLogin
    @RequestMapping("/viewHistory")
    public String viewHistory(HttpServletRequest req, Model model, int pageNum, int pageSize) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {

            Integer userId = (Integer) session.getAttribute("userId");

            ViewHistoryPaging viewHistoryPaging = viewHistoryService.selectViewHistoryByUserId(userId, pageNum, pageSize);
            if (viewHistoryPaging.getCommodityViewHistorys().size() > 0) {
                model.addAttribute("commodityViewHistorys", viewHistoryPaging.getCommodityViewHistorys());
                model.addAttribute("pageNum", pageNum);
                model.addAttribute("pageSize", pageSize);
                model.addAttribute("viewCount", viewHistoryPaging.getTotal());
                model.addAttribute("viewPageCount", (int) (viewHistoryPaging.getTotal() / pageSize) + 1);
            } else {
                //如果没有浏览记录
                model.addAttribute("commodityViewHistorys", "noView");
            }
            return "homeFramework/view-history";
        }
         return "homeFramework/login";

    }

    /**
     * 跳转收货地址页面
     */
    @NeedLogin
    @RequestMapping("/myAddress")
    public String myAddress(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {

            Integer userId = (Integer) session.getAttribute("userId");

            DeliveryAddressExample deliveryAddressExample = new DeliveryAddressExample();
            DeliveryAddressExample.Criteria criteria = deliveryAddressExample.createCriteria();
            criteria.andUserIdEqualTo((Integer) session.getAttribute("userId"));

            List<DeliveryAddress> deliveryAddresses = deliveryAddressService.selectByExample(deliveryAddressExample);

            model.addAttribute("AddressSize", deliveryAddresses.size());

            model.addAttribute("deliveryAddresses", deliveryAddresses);


            return "homeFramework/my-address";
        }
         return "homeFramework/login";

    }

    /**
     * 跳转购物车页面
     */
    @NeedLogin
    @RequestMapping("/myCart")
    public String myCart(HttpServletRequest req, Model model, int pageNum, int pageSize) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            //发送购物车信息
            Integer userId = (Integer) session.getAttribute("userId");
            CartExt cartExt = getCartByUserId(userId, pageNum, pageSize);
            if (cartExt.getCartSpeComs() != null) {
                model.addAttribute("allCart", cartExt.getCartSpeComs());
                model.addAttribute("cartIsNull", "have");
                model.addAttribute("size", cartExt.getCartSpeComs().size());
                model.addAttribute("allCount", getCartsCount(cartExt.getCartSpeComs()));
                model.addAttribute("allPrice", getCartsPrice(cartExt.getCartSpeComs()));
                model.addAttribute("pageNum", pageNum);
                model.addAttribute("pageSize", pageSize);
                model.addAttribute("cartCount", cartExt.getTotal());
                model.addAttribute("cartPageCount", (int) (cartExt.getTotal() / pageSize) + 1);
            } else {
                model.addAttribute("cartIsNull", null);
            }
            return "homeFramework/my-cart";
        }
         return "homeFramework/login";
    }

    /**
     * 跳转我的收藏页面
     */
    @NeedLogin
    @RequestMapping("/myCollect")
    public String myCollect(HttpServletRequest req, Model model, int pageNum, int pageSize) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {

            Integer userId = (Integer) session.getAttribute("userId");
            CommodityCollectPaging commodityCollectPaging = commodityCollectService.selectAllCommodityCollectComByUserId(userId, pageNum, pageSize);
            if (commodityCollectPaging.getCommodityCollectComExts().size() > 0) {

                model.addAttribute("commodityCollectComs", commodityCollectPaging.getCommodityCollectComExts());
                model.addAttribute("pageNum", pageNum);
                model.addAttribute("pageSize", pageSize);
                model.addAttribute("comCount", commodityCollectPaging.getTotal());
                model.addAttribute("comPageCount", (int) (commodityCollectPaging.getTotal() / pageSize) + 1);
            } else {
                //如果没有收藏商品或商品已经下架
                model.addAttribute("commodityCollectComs", "noCollect");
            }

            //收藏店铺查询信息
            StoreCollectPaging storeCollectPaging = storeCollectService.selsetStoreAndCollectByUserId(userId, pageNum, pageSize);
            if (storeCollectPaging.getStoreCollectExts().size() > 0) {
                model.addAttribute("storeCollectExts", storeCollectPaging.getStoreCollectExts());
                model.addAttribute("pageNum", pageNum);
                model.addAttribute("pageSize", pageSize);
                model.addAttribute("storeCount", storeCollectPaging.getTotal());
                model.addAttribute("storePageCount", (int) (storeCollectPaging.getTotal() / pageSize) + 1);
            } else {
                model.addAttribute("storeCollectExts", "noCollect");
            }


            return "homeFramework/my-collect";
        }
         return "homeFramework/login";
    }

    /**
     * 跳转到商品详情页
     *
     * @param commodityId 商品的id
     */

    @RequestMapping("/commodityInfo")
    public String commodityInfo(Integer commodityId, HttpServletRequest req, Model model) {
        HttpSession session = req.getSession(false);


        //查找商品评价
        List<EvaluateUserSpeComExt> evaluates = evaluateService.selectEvaluateByComId(commodityId);

        int s1 = 0;
        int s2 = 0;
        int s3 = 0;

        for (EvaluateUserSpeComExt e : evaluates) {
            EvaluatePicExample epe = new EvaluatePicExample();
            epe.createCriteria().andEvaluateIdEqualTo(e.getEvaluateId());
            List<EvaluatePic> evaluatePics = evaluatePicService.selectByExample(epe);
            if (evaluatePics.size() > 0) {
                e.setEvaluatePics(evaluatePics);
            }
            if (e.getEvaScore() != null && e.getEvaScore() >= 0 && e.getEvaScore() <= 5) {
                if (e.getEvaScore().equals(1)) {
                    s1++;
                } else if (e.getEvaScore().equals(5)) {
                    s3++;
                } else {
                    s2++;
                }
            }

        }
        model.addAttribute("evaluates", evaluates);
        model.addAttribute("s1", s1);
        model.addAttribute("s2", s2);
        model.addAttribute("s3", s3);
        model.addAttribute("evaluatePicsize", evaluates.size());


        //查找对应的店铺id
        Commodity commodity = commodityService.selectByPrimaryKey(commodityId);
        Integer storeId = commodity.getStoreId();
        //查找对应店铺id的店铺信息
        Store store = storeService.selectByPrimaryKey(storeId);
        model.addAttribute("store", store);

        //查询对商品id的商品信息
        model.addAttribute("commodity", commodity);

        //查询对商品id的商品信息和商品规格信息
        List<CommoditySpecification> commoditySpecifications = commodityService.selectAllCommSpeByKey(commodityId);

        //查看商品是否被收藏
        CommodityCollectExample commodityCollectExample = new CommodityCollectExample();
        CommodityCollectExample.Criteria criteria = commodityCollectExample.createCriteria();
        criteria.andCommodityIdEqualTo(commodityId);
        List<CommodityCollect> commodityCollects = commodityCollectService.selectByExample(commodityCollectExample);
        if (commodityCollects.size() > 0) {
            model.addAttribute("isCollected", true);
        } else {
            model.addAttribute("isCollected", false);
        }
        model.addAttribute("commoditySpecification", commoditySpecifications);

        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            //添加到浏览记录

            ViewHistoryExample viewHistoryExample = new ViewHistoryExample();
            ViewHistoryExample.Criteria criteria1 = viewHistoryExample.createCriteria();
            criteria1.andCommodityIdEqualTo(commoditySpecifications.get(0).getCommodityId());
            List<ViewHistory> viewHistories = viewHistoryService.selectByExample(viewHistoryExample);
            if (viewHistories.size() <= 0) {
                //如果没有浏览过
                ViewHistory viewHistory = new ViewHistory();
                viewHistory.setUserId(userId);
                viewHistory.setCommodityId(commoditySpecifications.get(0).getCommodityId());
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
                viewHistory.setViewTime(dateFormat.format(date));
                viewHistoryService.insertSelective(viewHistory);
            } else {
                //如果浏览过
                ViewHistory viewHistory = new ViewHistory();
                viewHistory.setId(viewHistories.get(0).getId());
                viewHistory.setUserId(userId);
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
                viewHistory.setViewTime(dateFormat.format(date));
                viewHistoryService.updateByPrimaryKeySelective(viewHistory);
            }

        }
        return "homeFramework/commodity-info";
    }


    /**
     * 跳转我的评价页面
     */
    @NeedLogin
    @RequestMapping("/myEvaluate")
    public String myEvaluate(HttpServletRequest req, Model model, int pageNum, int pageSize) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");

            EvaluateUserSpeComExtPaging evaluateUserSpeComExtPaging = evaluateService.selectAllEvaluateByUserIdPaging(userId, pageNum, pageSize);

            //设置购买时间和购买数量

            for (EvaluateUserSpeComExt es : evaluateUserSpeComExtPaging.getEvaluateUserSpeComExts()) {
                OrdersComSpeAddress ordersComSpeAddress = ordersService.selectAllOrdersByKey(es.getOrderId());
                if (ordersComSpeAddress != null) {
                    es.setBuyTime(ordersComSpeAddress.getPayDate());

                    CommodityOrdersExample commodityOrdersExample = new CommodityOrdersExample();
                    commodityOrdersExample.createCriteria().andSpecificationIdEqualTo(es.getSpecificationId())
                            .andOrdersIdEqualTo(es.getOrderId());
                    List<CommodityOrders> commodityOrders = commodityOrdersService.selectByExample(commodityOrdersExample);

                    if (commodityOrders.size() > 0)
                        es.setBeBuyCount(commodityOrders.get(0).getCommodityCount());
                }

                //添加评论图片

                EvaluatePicExample evaluatePicExample = new EvaluatePicExample();
                evaluatePicExample.createCriteria().andEvaluateIdEqualTo(es.getEvaluateId());

                List<EvaluatePic> evaluatePics = evaluatePicService.selectByExample(evaluatePicExample);
                es.setEvaluatePics(evaluatePics);
            }


            model.addAttribute("euscs", evaluateUserSpeComExtPaging.getEvaluateUserSpeComExts());
            model.addAttribute("total", evaluateUserSpeComExtPaging.getTotal());
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("evaPageCount", (int) (evaluateUserSpeComExtPaging.getTotal() / pageSize) + 1);
            if(evaluateUserSpeComExtPaging.getEvaluateUserSpeComExts().size()<0){
                model.addAttribute("evaCount","null");
            }
            return "homeFramework/my-evaluate";
        }

        return "homeFramework/login";
    }


    @RequestMapping("/store")
    public String store(Integer storeId, HttpServletRequest req, Model model) {

        return "homeFramework/store";
    }

    @RequestMapping("/home1")
    public String home1() {

        return "homeFramework/home1";
    }

    /**
     * 提交订单页面
     *
     * @param allCheckCartId
     * @return
     */
    @NeedLogin
    @RequestMapping("/myOrdersFill")
    public String myOrdersFill(HttpServletRequest req, Model model, String allCheckCartId) {
        //收货地址信息
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {

            //查询地址信息
            DeliveryAddressExample deliveryAddressExample = new DeliveryAddressExample();
            DeliveryAddressExample.Criteria criteria = deliveryAddressExample.createCriteria();
            criteria.andUserIdEqualTo((Integer) session.getAttribute("userId"));

            List<DeliveryAddress> deliveryAddresses = deliveryAddressService.selectByExample(deliveryAddressExample);

            model.addAttribute("size", deliveryAddresses.size());

            model.addAttribute("deliveryAddresses", deliveryAddresses);

            if (allCheckCartId != "") {
                //查询商品信息
                String[] allCheckIdAndCounts = allCheckCartId.split(",");
                List<CartSpeCom> cartSpeComs = new ArrayList<>();
                Double allSumPrice = 0.00;
                Double allSumFreight = 0.00;
                Integer allCount = 0;
                for (int i = 0; i < allCheckIdAndCounts.length; i++) {
                    Integer cartId = Integer.valueOf(allCheckIdAndCounts[i]);
                    Cart cart = cartService.selectByPrimaryKey(cartId);

                    Integer specificationId = cart.getSpecificationId();
                    Integer commodityCount = cart.getCommodityCount();
                    CommoditySpecification cs = commoditySpecificationServiceExt.selectAllCommSpeBySpecificationKey(specificationId);
                    CartSpeCom cartSpeCom = new CartSpeCom(cs);
                    cartSpeCom.setCommodityCount(commodityCount);
                    cartSpeCom.setSumPrice(new BigDecimal(cartSpeCom.getCommodityCount() * cartSpeCom.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    if (cartSpeCom.getCommodityCount() != null) {
                        allCount += cartSpeCom.getCommodityCount();
                    } else {
                        allCount += 0;
                    }

                    if (cartSpeCom.getPrice() != null) {
                        allSumPrice += cartSpeCom.getSumPrice();
                    } else {
                        allSumPrice += 0.00;
                    }

                    if (cartSpeCom.getFreight() != null) {
                        allSumFreight += cartSpeCom.getFreight();
                    } else {
                        allSumFreight += 0.00;
                    }
                    cartSpeComs.add(cartSpeCom);

                }

                model.addAttribute("size", allCount);
                model.addAttribute("allSumPrice", new BigDecimal(allSumPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                model.addAttribute("allSumFreight", new BigDecimal(allSumFreight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                model.addAttribute("allPayPrice", new BigDecimal(allSumPrice - allSumFreight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                model.addAttribute("SpeComs", cartSpeComs);
                model.addAttribute("allCheckCartId", allCheckCartId);
                model.addAttribute("orderId", null);
            } else {
                model.addAttribute("SpeComs", null);
            }

            //搜索商家信息

            return "homeFramework/my-orders-fill";


        }
         return "homeFramework/login";
    }



    /**
     * 通过orderId
     * <p>
     * 提交订单页面，通过订单id
     *
     * @param orderId
     */
    @NeedLogin
    @RequestMapping("/ByOrdersFill")
    public String ByOrdersFill(HttpServletRequest req, Model model, Integer orderId) {
        //收货地址信息
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            //查询地址信息
            DeliveryAddressExample deliveryAddressExample = new DeliveryAddressExample();
            DeliveryAddressExample.Criteria criteria = deliveryAddressExample.createCriteria();
            criteria.andUserIdEqualTo(userId);

            List<DeliveryAddress> deliveryAddresses = deliveryAddressService.selectByExample(deliveryAddressExample);

            model.addAttribute("size", deliveryAddresses.size());

            model.addAttribute("deliveryAddresses", deliveryAddresses);

            if (orderId != null) {

                OrdersComSpeAddress ordersComSpeAddress = ordersService.selectAllOrdersByKey(orderId);
                if (userId.equals(ordersComSpeAddress.getUserId())) {

                    int allCount = 0;
                    Double allSumPrice = ordersComSpeAddress.getSumPrice();
                    Double allPayPrice = ordersComSpeAddress.getSumPrice();
                    List<CartSpeCom> cartSpeComs = new ArrayList<>();
                    List<CommoditySpecification> commoditySpecifications = new ArrayList<>();
                    CommodityOrdersExample commodityOrdersExample = new CommodityOrdersExample();
                    commodityOrdersExample.createCriteria().andOrdersIdEqualTo(orderId);
                    List<CommodityOrders> commodityOrders = commodityOrdersService.selectByExample(commodityOrdersExample);
                    for (CommodityOrders cos : commodityOrders) {

                        CommoditySpecification commoditySpecification = commodityService.selectAllCommSpeBySpecificationKey(cos.getSpecificationId());
                        commoditySpecification.setCommodityCount(cos.getCommodityCount());
                        commoditySpecifications.add(commoditySpecification);

                    }
                    ordersComSpeAddress.setCommoditySpecifications(commoditySpecifications);
                    ordersComSpeAddress.setCommodityCount(commoditySpecifications.size());

                    CartSpeCom cartSpeCom = new CartSpeCom();
                    cartSpeCom.setUserId(userId);
                    cartSpeCom.setSumPrice(ordersComSpeAddress.getSumPrice());
                    cartSpeCom.setCommodityCount(commoditySpecifications.size());
                    for (CommoditySpecification cs : ordersComSpeAddress.getCommoditySpecifications()) {
                        cartSpeCom.setCommoditySpecification(cs);
                        cartSpeComs.add(cartSpeCom);
                    }

                    model.addAttribute("size", allCount);
                    model.addAttribute("allSumPrice", allSumPrice);
                    model.addAttribute("allSumFreight", 0.00);
                    model.addAttribute("allPayPrice", allPayPrice);
                    model.addAttribute("SpeComs", cartSpeComs);
                    model.addAttribute("allCheckCartId", null);
                    model.addAttribute("orderId", orderId);

                } else {
                    model.addAttribute("isUser", false);
                }
            } else {
                model.addAttribute("SpeComs", null);
            }

            //搜索商家信息

            return "homeFramework/my-orders-fill";


        }
         return "homeFramework/login";
    }

    /**
     * 订单提交成功，跳转支付页面
     *
     * @param allCheckCartId 选择的id
     * @param addressId      地址id
     */
    @NeedLogin
    @RequestMapping("/PayOrder")
    public String PayOrder(HttpServletRequest req, HttpServletResponse resp, Model model, String allCheckCartId, String addressId) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //收货地址信息
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            //查询地址信息
            Integer integerAddressId = Integer.valueOf(addressId);
            DeliveryAddress deliveryAddress = deliveryAddressService.selectByPrimaryKey(integerAddressId);

            model.addAttribute("deliveryAddress", deliveryAddress);
            if (userId.equals(deliveryAddress.getUserId())) {
                if (allCheckCartId != "") {
                    //查询商品信息
                    String[] allCheckIdAndCounts = allCheckCartId.split(",");
                    List<CartSpeCom> cartSpeComs = new ArrayList<>();
                    Double allSumPrice = 0.00;
                    Double allSumFreight = 0.00;
                    Integer allCount = 0;
                    for (int i = 0; i < allCheckIdAndCounts.length; i++) {
                        Integer cartId = Integer.valueOf(allCheckIdAndCounts[i]);
                        Cart cart = cartService.selectByPrimaryKey(cartId);

                        Integer specificationId = cart.getSpecificationId();
                        Integer commodityCount = cart.getCommodityCount();
                        CommoditySpecification cs = commoditySpecificationServiceExt.selectAllCommSpeBySpecificationKey(specificationId);
                        CartSpeCom cartSpeCom = new CartSpeCom(cs);
                        cartSpeCom.setCommodityCount(commodityCount);
                        cartSpeCom.setSumPrice(new BigDecimal(cartSpeCom.getCommodityCount() * cartSpeCom.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        if (cartSpeCom.getCommodityCount() != null) {
                            allCount += cartSpeCom.getCommodityCount();
                        } else {
                            allCount += 0;
                        }

                        if (cartSpeCom.getPrice() != null) {
                            allSumPrice += cartSpeCom.getSumPrice();
                        } else {
                            allSumPrice += 0.00;
                        }

                        if (cartSpeCom.getFreight() != null) {
                            allSumFreight += cartSpeCom.getFreight();
                        } else {
                            allSumFreight += 0.00;
                        }
                        cartSpeComs.add(cartSpeCom);

                    }
                    //查询用户余额
                    User user = userService.selectByPrimaryKey(userId);
                    Double remain = user.getRemain();


                    //将商品信息添加到订单表中
                    Integer orderId = UUID.randomUUID().toString().hashCode();
                    if (orderId < 0) {//有可能是负数
                        orderId = -orderId;
                    }
                    Orders order = new Orders();
                    order.setId(orderId);
                    order.setUserId(userId);
                    order.setDeliveryAddressId(integerAddressId);
                    order.setPayType(1);
                    order.setOrderStatus(0);
                    order.setSumPrice(new BigDecimal(allSumPrice - allSumFreight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    Date date = new Date();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:MM:ss");
                    order.setOrderDate(dateFormat.format(date));
                    int res = ordersService.insertSelective(order);

                    if (res > 0) {

                        for (int i = 0; i < cartSpeComs.size(); i++) {
                            //将商品信息插入到商品信息表中
                            CommodityOrders commodityOrders = new CommodityOrders();
                            commodityOrders.setOrdersId(orderId);
                            commodityOrders.setCommodityId(cartSpeComs.get(i).getCommodityId());
                            commodityOrders.setSpecificationId(cartSpeComs.get(i).getSpecificationId());
                            commodityOrders.setCommodityCount(cartSpeComs.get(i).getCommodityCount());
                            commodityOrdersService.insertSelective(commodityOrders);

                            Specification specification = new Specification();
                            specification.setId(cartSpeComs.get(i).getSpecificationId());
                            if (specificationService.selectByPrimaryKey(cartSpeComs.get(i).getSpecificationId()).getInventory()!=null)
                                specification.setInventory(specificationService.selectByPrimaryKey(cartSpeComs.get(i).getSpecificationId()).getInventory()-1);
                            specificationService.updateByPrimaryKeySelective(specification);


                        }
                    }

                    model.addAttribute("toType", "cart");
                    model.addAttribute("orderId", orderId);
                    model.addAttribute("remain", remain);
                    model.addAttribute("size", allCount);
                    model.addAttribute("allSumPrice", new BigDecimal(allSumPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    model.addAttribute("allSumFreight", new BigDecimal(allSumFreight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    model.addAttribute("allPayPrice", new BigDecimal(allSumPrice - allSumFreight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    model.addAttribute("SpeComs", cartSpeComs);

                } else {
                    model.addAttribute("SpeComs", null);
                }
            } else {
                model.addAttribute("isUser", false);
            }

            return "homeFramework/my-orders-success";
        }
         return "homeFramework/login";
    }

    /**
     * 根据orderId
     * 订单提交成功，跳转支付页面
     *
     * @param orderId 订单的id
     */
    @NeedLogin
    @RequestMapping("/PayOrderByOrderId")
    public String PayOrderByOrderId(HttpServletRequest req, HttpServletResponse resp, Model model, Integer orderId) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //收货地址信息
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            OrdersComSpeAddress ordersComSpeAddress = ordersService.selectAllOrdersByKey(orderId);
            if (userId.equals(ordersComSpeAddress.getUserId())) {
                Orders o = new Orders();
                o.setId(orderId);
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
                o.setOrderDate(dateFormat.format(date));
                o.setOrderStatus(0);
                int i = ordersService.updateByPrimaryKeySelective(o);
                if (i > 0) {

                    List<CommoditySpecification> commoditySpecifications = new ArrayList<>();

                    CommodityOrdersExample commodityOrdersExample = new CommodityOrdersExample();
                    commodityOrdersExample.createCriteria().andOrdersIdEqualTo(ordersComSpeAddress.getOrdersId());
                    List<CommodityOrders> commodityOrders = commodityOrdersService.selectByExample(commodityOrdersExample);
                    for (CommodityOrders cos : commodityOrders) {

                        CommoditySpecification commoditySpecification = commodityService.selectAllCommSpeBySpecificationKey(cos.getSpecificationId());
                        commoditySpecification.setCommodityCount(cos.getCommodityCount());
                        commoditySpecifications.add(commoditySpecification);

                    }
                    ordersComSpeAddress.setCommoditySpecifications(commoditySpecifications);

                    //查询用户余额
                    User user = userService.selectByPrimaryKey(userId);
                    Double remain = user.getRemain();

                    model.addAttribute("toType", "order");
                    model.addAttribute("remain", remain);
                    model.addAttribute("orderId", orderId);
                    model.addAttribute("allPayPrice", ordersComSpeAddress.getSumPrice());
                    model.addAttribute("ordersComSpeAddress", ordersComSpeAddress);
                } else {
                    model.addAttribute("error", "error");
                }
            } else {
                model.addAttribute("isUser", false);
            }


            return "homeFramework/my-orders-success";
        }
         return "homeFramework/login";

    }

    /**
     * 根据orderId+addressId
     * 订单提交成功，跳转支付页面
     *
     * @param orderId   订单的id
     * @param addressId 新的地址id
     */
    @NeedLogin
    @RequestMapping("/PayOrderaByOrderId")
    public String PayOrderaByOrderId(HttpServletRequest req, HttpServletResponse resp, Model model, Integer
            orderId, Integer addressId) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //收货地址信息
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            OrdersComSpeAddress ordersComSpeAddress = ordersService.selectAllOrdersByKey(orderId);
            if (userId.equals(ordersComSpeAddress.getUserId())) {
                Orders o = new Orders();
                o.setId(orderId);
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
                o.setOrderDate(dateFormat.format(date));
                o.setOrderStatus(0);
                int i = ordersService.updateByPrimaryKeySelective(o);
                if (i > 0) {
                    List<CommoditySpecification> commoditySpecifications = new ArrayList<>();

                    CommodityOrdersExample commodityOrdersExample = new CommodityOrdersExample();
                    commodityOrdersExample.createCriteria().andOrdersIdEqualTo(ordersComSpeAddress.getOrdersId());
                    List<CommodityOrders> commodityOrders = commodityOrdersService.selectByExample(commodityOrdersExample);
                    for (CommodityOrders cos : commodityOrders) {

                        CommoditySpecification commoditySpecification = commodityService.selectAllCommSpeBySpecificationKey(cos.getSpecificationId());
                        commoditySpecification.setCommodityCount(cos.getCommodityCount());
                        commoditySpecifications.add(commoditySpecification);

                    }
                    ordersComSpeAddress.setCommoditySpecifications(commoditySpecifications);


                    DeliveryAddress deliveryAddress = deliveryAddressService.selectByPrimaryKey(addressId);
                    if (deliveryAddress != null && userId.equals(deliveryAddress.getUserId())) {
                        ordersComSpeAddress.setDeliveryAddressId(addressId);
                        ordersComSpeAddress.setUserId(userId);
                        ordersComSpeAddress.setReceiver(deliveryAddress.getReceiver());
                        ordersComSpeAddress.setProvince(deliveryAddress.getProvince());
                        ordersComSpeAddress.setCity(deliveryAddress.getCity());
                        ordersComSpeAddress.setArea(deliveryAddress.getArea());
                        ordersComSpeAddress.setAddress(deliveryAddress.getAddress());
                        ordersComSpeAddress.setPhone(deliveryAddress.getPhone());
                        ordersComSpeAddress.setPostcode(deliveryAddress.getPostcode());
                    }
                    //查询用户余额
                    User user = userService.selectByPrimaryKey(userId);
                    Double remain = user.getRemain();

                    model.addAttribute("toType", "order");
                    model.addAttribute("remain", remain);
                    model.addAttribute("orderId", orderId);
                    model.addAttribute("allPayPrice", ordersComSpeAddress.getSumPrice());
                    model.addAttribute("ordersComSpeAddress", ordersComSpeAddress);
                } else {
                    model.addAttribute("error", "error");
                }
            } else {
                model.addAttribute("isUser", false);
            }


            return "homeFramework/my-orders-success";
        }
         return "homeFramework/login";

    }

    @RequestMapping("/test")
    public String test() {
        return "homeFramework/test";
    }

    @RequestMapping("/allClass")
    public String allClass() {
        return "homeFramework/all-class";
    }

    /**
     * 跳转到搜索
     *
     * @param name 搜索内容
     * @param type 搜索类型
     *             0：默认
     *             1：按销量
     *             2：按售价
     *             3：按浏览量
     *             4：搜索中再搜索
     */
    @RequestMapping("/searchPage")
    public String searchPage(HttpServletRequest req, Model model, String name,String sort, int pageNum, int pageSize, Integer type) {
        SearchCommodity searchCommodity = null;
        if (type == 0) {
            searchCommodity = searchServiceExt.searchByName(name,sort, pageNum, pageSize);
            model.addAttribute("sort", "desc");
            model.addAttribute("Rsort", "true");
        } else if (type == 1) {
            searchCommodity = searchServiceExt.searchedByBuyCount(name,sort, pageNum, pageSize);
            model.addAttribute("sort", sort);
            model.addAttribute("Rsort", "false");
        } else if (type == 2) {
            searchCommodity = searchServiceExt.searchedByPrice(name,sort, pageNum, pageSize);
            model.addAttribute("sort", sort);
            model.addAttribute("Rsort", "false");
        } else if (type == 3) {
            searchCommodity = searchServiceExt.searchedByViewCount(name,sort, pageNum, pageSize);
            model.addAttribute("sort", sort);
            model.addAttribute("Rsort", "false");
        } else if (type == 4) {

            searchCommodity = searchServiceExt.searchedByPrice(name,sort, pageNum, pageSize);
            model.addAttribute("sort", sort);
            model.addAttribute("Rsort", "false");
        }


        long commodityPageCount = searchCommodity.getTotal() / pageSize;
        if(searchCommodity.getTotal() % pageSize!=0){
            commodityPageCount++;
        }
        model.addAttribute("name", name);
        model.addAttribute("type", type);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("commodities", searchCommodity.getCommodities());
        model.addAttribute("commodityCount", searchCommodity.getTotal());
        model.addAttribute("commodityPageCount", commodityPageCount);

        return "homeFramework/search3";
    }

    /**
     * 按价格区间跳转到搜索
     *  type=5
     */
    @RequestMapping("/searchPage2")
    public String searchPage2(HttpServletRequest req, Model model, String name,Double maxPrice,Double minPrice,  int pageNum, int pageSize) {
        SearchCommodity searchCommodity = searchServiceExt.searchedByMaxMinPrice(name,maxPrice,minPrice,pageNum,pageSize);
        long commodityPageCount = searchCommodity.getTotal() / pageSize;
        if(searchCommodity.getTotal() % pageSize!=0){
            commodityPageCount++;
        }
        model.addAttribute("name", name);
        model.addAttribute("type", 5);
        model.addAttribute("maxPrice", maxPrice);
        model.addAttribute("minPrice", minPrice);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("commodities", searchCommodity.getCommodities());
        model.addAttribute("commodityCount", searchCommodity.getTotal());
        model.addAttribute("commodityPageCount", commodityPageCount);

        return "homeFramework/search3";
    }
    /**
     * 跳转到我的订单页面
     *
     * @param req
     * @param model //     * @param pageNum
     *              //     * @param pageSize
     * @return
     */
    @NeedLogin
    @RequestMapping("/myOrder")
    public String myOrder(HttpServletRequest req, Model model) {

        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");

            int sc0 = 0;
            int sc1 = 0;
            int sc2 = 0;
            int sc3 = 0;
            int sc4 = 0;
            int sc5 = 0;
            List<OrdersComSpeAddress> ordersComSpeAddresses = ordersService.selectAllOrdersByUserId(userId);

            for (OrdersComSpeAddress ocsa : ordersComSpeAddresses) {
                List<CommoditySpecification> commoditySpecifications = new ArrayList<>();
                CommodityOrdersExample commodityOrdersExample = new CommodityOrdersExample();
                commodityOrdersExample.createCriteria().andOrdersIdEqualTo(ocsa.getOrdersId());
                List<CommodityOrders> commodityOrders = commodityOrdersService.selectByExample(commodityOrdersExample);
                for (CommodityOrders cos : commodityOrders) {

                    CommoditySpecification commoditySpecification = commodityService.selectAllCommSpeBySpecificationKey(cos.getSpecificationId());
                    if (commoditySpecification != null) {
                        if (ocsa.getOrderStatus().equals(3)) {
                            //如果已经评价
                            if (isHavaEva(userId, ocsa.getOrdersId(), cos.getSpecificationId())) {
                                commoditySpecification.setIsEvaluate(1);
                            } else
                                commoditySpecification.setIsEvaluate(0);

                        }
                        commoditySpecification.setCommodityCount(cos.getCommodityCount());
                        commoditySpecifications.add(commoditySpecification);
                    }


                }
                ocsa.setCommoditySpecifications(commoditySpecifications);
                ocsa.setCommodityCount(commoditySpecifications.size());

                //查询service信息
                Service service = serviceService.selectByPrimaryKey(ocsa.getServiceId());

                ocsa.setService(service);
                if (ocsa.getOrderStatus() == 0) {
                    sc0++;
                } else if (ocsa.getOrderStatus() == 1) {
                    sc1++;
                } else if (ocsa.getOrderStatus() == 2) {
                    sc2++;
                } else if (ocsa.getOrderStatus() == 3) {
                    sc3++;
                } else if (ocsa.getOrderStatus() == 4) {
                    sc4++;
                } else if (ocsa.getOrderStatus() == 5) {
                    sc5++;
                }

                if (ocsa.getService() != null && ocsa.getService().getServiceStatus() == 2) {

                    ocsa.setIsServiced("yes");

                }
            }


            model.addAttribute("sc0", sc0);
            model.addAttribute("sc1", sc1);
            model.addAttribute("sc2", sc2);
            model.addAttribute("sc3", sc3);
            model.addAttribute("sc4", sc4);
            model.addAttribute("sc5", sc5);

            model.addAttribute("ordersComSpeAddresses", ordersComSpeAddresses);


            return "homeFramework/my-orders-list";
        } else {
            return "redirect:login";
        }

    }

    /**
     * 跳转到我要评价子页面
     *
     * @param req
     * @param model
     * @param specificationId 商品规格id
     * @return
     */
    @NeedLogin
    @RequestMapping("/fillEvaluate")
    public String fillEvaluate(HttpServletRequest req, Model model, Integer orderId, Integer specificationId, String type) {

        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            if (type.equals("l")) {
                EvaluateUserSpeComExt evaluateUserSpeCom = evaluateService.selectEvaluateByUserSpeId(userId, orderId, specificationId);

                EvaluatePicExample evaluatePicExample = new EvaluatePicExample();
                evaluatePicExample.createCriteria().andEvaluateIdEqualTo(evaluateUserSpeCom.getEvaluateId());
                List<EvaluatePic> evaluatePics = evaluatePicService.selectByExample(evaluatePicExample);
                evaluateUserSpeCom.setEvaluatePics(evaluatePics);

                model.addAttribute("evaScore", evaluateUserSpeCom.getEvaScore());

                model.addAttribute("evaluateUserSpeCom", evaluateUserSpeCom);
            } else
                model.addAttribute("evaScore", -1);
            model.addAttribute("type", type);
            model.addAttribute("orderId", orderId);
            model.addAttribute("specificationId", specificationId);
            return "homeFramework/fill-evaluate";
        }
         return "homeFramework/login";
    }


    @RequestMapping("/storeAbout")
    public String storeAbout() {
        return "homeFramework/store-about";
    }

    @RequestMapping("/storeApply")
    public String storeApply() {
        return "homeFramework/store-apply";
    }

    @RequestMapping("/request")
    public String request() {
        return "homeFramework/request";
    }

    @RequestMapping("/rsaAes")
    @NeedLogin
    public String rsaAes(String test) {
        return "homeFramework/rsaAes";
    }

    /**
     * 跳转我的订单页面
     *
     * @param req
     * @param model
     * @param pageNum
     * @param pageSize
     * @return
     */
    @NeedLogin
    @RequestMapping("/cart")
    public String cart(HttpServletRequest req, Model model, int pageNum, int pageSize) {

        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            //发送购物车信息
            Integer userId = (Integer) session.getAttribute("userId");
            CartExt cartExt = getCartByUserId(userId, pageNum, pageSize);
            if (cartExt != null&&cartExt.getCartSpeComs().size()>0) {
                model.addAttribute("allCart", cartExt.getCartSpeComs());
                model.addAttribute("cartIsNull", "notNull");
                model.addAttribute("size", cartExt.getCartSpeComs().size());
                model.addAttribute("allCount", getCartsCount(cartExt.getCartSpeComs()));
                model.addAttribute("allPrice", getCartsPrice(cartExt.getCartSpeComs()));
            } else {
                model.addAttribute("cartIsNull", "null");
            }
        } else {
            model.addAttribute("cartIsNull", "null");
        }
        return "homeFramework/cart";
    }

    @RequestMapping("/firstType")
    public String firstType(HttpServletRequest req, Model model, Integer categoryId, int pageNum, int pageSize) {

        if(getCategoryLevel(categoryId).equals(2)){
            return "redirect:secondType?categoryId="+categoryId+"&pageNum=1&pageSize=16";
        }

        //查找一级分类信息
        List<Category> allCategories = categoryService.selectByExample(new CategoryExample());

        Iterator<Category> iterator = allCategories.iterator();
        while (iterator.hasNext()) {
            Category nextCate = iterator.next();
            if (!getCategoryLevel(nextCate.getId()).equals(1)) {
                iterator.remove();
            }

        }

        //查找子分类id
        List<Integer> categoryIds = new ArrayList<>();
        Category category = categoryService.selectByPrimaryKey(categoryId);
        String catetoryName = category.getName();
        if (category != null) {
            CategoryExample ce = new CategoryExample();
            ce.createCriteria().andParentCategoryEqualTo(categoryId);
            List<Category> cs = categoryService.selectByExample(ce);
            if (cs.size()>0) {
                for (int i=0;i<cs.size();i++)
                    categoryIds.add(cs.get(i).getId());
            }
        }


        //查找对应分类的商品
        CommodityExample commodityExample = new CommodityExample();
        commodityExample.createCriteria().andCatetoryIdIn(categoryIds);
        commodityExample.setOrderByClause("bay_count desc");
        CommodityPaging commodityPaging = commodityService.selectByExample(commodityExample, pageNum, pageSize);

        long commodityPageCount = commodityPaging.getTotal() / pageSize;
        if(commodityPaging.getTotal() % pageSize!=0){
            commodityPageCount++;
        }
        model.addAttribute("allCategories", allCategories);
        model.addAttribute("catetoryName", catetoryName);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("commodities", commodityPaging.getCommodities());


        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("commodityCount", commodityPaging.getTotal());
        model.addAttribute("commodityPageCount", commodityPageCount);

        return "homeFramework/first-type";
    }

    @RequestMapping("/secondType")
    public String secondType(HttpServletRequest req, Model model, Integer categoryId, int pageNum, int pageSize) {
        //查询
        Category category = categoryService.selectByPrimaryKey(categoryId);
        List<Category> categories;
        if(category!=null){
            if(getCategoryLevel(categoryId).equals(1)){
                return "redirect:firstType?categoryId="+categoryId+"&pageNum=1&pageSize=24";
            }
            Category Pcatetory = categoryService.selectByPrimaryKey(category.getParentCategory());


            String catetoryName = category.getName();
            CategoryExample categoryExample = new CategoryExample();
            categoryExample.createCriteria().andParentCategoryEqualTo(category.getParentCategory());
             categories= categoryService.selectByExample(categoryExample);


             //查询对应分类的商品
            CommodityExample commodityExample = new CommodityExample();
            commodityExample.createCriteria().andCatetoryIdEqualTo(categoryId);
            CommodityPaging commodityPaging = commodityService.selectByExample(commodityExample, pageNum, pageSize);
            long commodityPageCount = commodityPaging.getTotal() / pageSize;
            if(commodityPaging.getTotal() % pageSize!=0){
                commodityPageCount++;
            }


            model.addAttribute("categories",categories);
            model.addAttribute("commodities",commodityPaging.getCommodities());
            model.addAttribute("catetoryName", catetoryName);
            model.addAttribute("Pcatetory", Pcatetory);


            model.addAttribute("categoryId", categoryId);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("commodityCount", commodityPaging.getTotal());
            model.addAttribute("commodityPageCount", commodityPageCount);
        }else{
            model.addAttribute("categories","null");
        }

        return "homeFramework/second-type";
    }

    @RequestMapping("/payOrder")
    public String payOrder (){
        return "homeFramework/payOrder";
    }
}
